package com.pz.dx.dxm.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.pz.dx.common.utils.R;
import com.pz.dx.dxm.controller.vo.LoginRes;
import com.pz.dx.dxm.controller.vo.opinion.HandleOpinionReq;
import com.pz.dx.dxm.controller.vo.opinion.OpinionAddReq;
import com.pz.dx.dxm.controller.vo.opinion.OpinionListRes;
import com.pz.dx.dxm.entity.OpinionEntity;
import com.pz.dx.dxm.service.OpinionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class OpinionController {
    @Autowired
    private OpinionService opinionService;
    @Autowired
    private LoginController loginController;

    @PostMapping("/dx-m/option/add")
    public R addOpinion(@RequestBody OpinionAddReq req){
        loginController.checkLoginStatus();

        LoginRes.UserSession userSession = loginController.getUserSession();
        if(userSession == null){
            return R.error();
        }
        Long userId = userSession.getUserId();
        opinionService.addOpinion(userId, req);
        return R.ok();
    }

    @GetMapping("/dx-m/option/getOne")
    public R getOneOpinion(@RequestParam("opinionId")String opinionId){
        OpinionEntity oneOpinion = opinionService.getOneOpinion(opinionId);
        return R.okData(oneOpinion);
    }

    /**
     * 获取opinion列表
     * @param model 获取模式
     *                  1：普通获取所有处理中和结束的opinion
     *                  2: 获取userId主动发送的opinion
     *                  3：获取所有新建的opinion（level为2的用户才能获取）
     *                  4：根据opinionId精准获取
     * @param opinionId 当model为3时不为空
     */
    @GetMapping("/dx-m/option/list")
    public R listOpinion(@RequestParam("model")int model, @RequestParam("opinionId")Long opinionId){
        Long userId = null;
        if(StpUtil.isLogin()){
            userId = loginController.getUserSession().getUserId();
        }
        List<OpinionListRes> ans = opinionService.listOpinion(model, opinionId, userId);
        return R.okData(ans);
    }

    /**
     * 处理opinion: 删除或更新
     * @return
     */
    @PostMapping("/dx-m/option/handle")
    public R updateOpinion(@RequestBody HandleOpinionReq req){
        loginController.checkLoginStatus();

        LoginRes.UserSession userSession = loginController.getUserSession();
        if(userSession == null){
            return R.error();
        }
        // TODO: 校验用户权限

        opinionService.handleOpinion(req);
        return R.ok();
    }
}
